// pages/view/view.js
var Parser = require("../../libs/dom-parser");
var WxParse = require('../../libs/wxParse.js');
var utils = require('../../utils/util.js');
//var base64 = require('../../libs/base64.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    newsId: 0,
    author: "",
    title: "...",
    fontSize: 18,
    qrcode: "",
    items: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var then = this;
    console.log(options)
    var id = options.id.split('_'),
      chid = options.chid,
      navid = options.navid
    //console.log(id)
    options && options.id && this.setData({
      newsId: id.length > 1 ? id[1] : id[0],
      channelId: chid,
      navId: navid
      //author: options.author || ""
    })
    //console.log(this.data)
    /*var scene = decodeURIComponent(options.scene);
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={{appid}}&secret={{appsecret}}'.tmpl({
        appid: 'wx25371c74b74ebb96',
        appsecret: 'd657936f445906cbabd5b3e7f62db209'
      }),
      data: {},
      success: function (res) {
        console.log(res.data.access_token)
        wx.request({
          url: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={{token}}'.tmpl({
            token: res.data.access_token
          }),
          data: {
            path: "pages/view/view?id=" + (id.length > 1 ? id[1] : id[0]) + "&chid=" + chid + "&navid=" + navid,
            width: 430,
            scene: scene
          },
          method: "POST",
          success: function (res) {
            console.log(res)

            var fr = res.data;
            then.setData({
              qrcode: fr
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })*/
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var then = this;
    wx.getStorage({
      key: 'fontsize',
      success: function (res) {
        then.setData({
          fontSize: parseInt(res.data)
        })
      },
    })
    this.initDataView();
    this.getAsideNews();


    /*utils.qrcode('identify', {
      width: 128,
      height: 128,
      text: "../../pages/view/view?id=" + this.data.newsId + "&chid=" + this.data.channelId + "&navid=" + this.data.navId
    }, function (img) {
      console.log(img)
      then.setData({
        qrcode: img
      });
    });*/

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.initDataView();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "邀你一起看",//"和讯网 - " + this.data.title,
      path: "/pages/index/index?type=" + this.data.channelId + "&i=" + this.data.navId + "&id=" + this.data.newsId,
      success: function (res) {
        wx.showToast({
          title: '转发成功',
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '转发失败',
        })
      }
    }
  },
  initDataView: function () {
    wx.showNavigationBarLoading()
    var then = this;
    wx.setNavigationBarTitle({
      title: '和讯网'//this.data.title,
    })
    wx.request({
      url: utils.api.newsView.tmpl({
        id: this.data.newsId
      }),
      data: {},
      success: function (res) {
        var XmlParser = new Parser.DOMParser();
        var doc = XmlParser.parseFromString(res.data);
        var title = doc.getElementsByTagName('title');
        var content = doc.getElementsByTagName('content');
        var picture = doc.getElementsByTagName('picture');
        var date = doc.getElementsByTagName('date');
        var media = doc.getElementsByTagName('medianame');
        var subtype = doc.getElementsByTagName('subtype');
        var url = doc.getElementsByTagName('url');
        //console.log(title, content, picture, date)
        console.log(/caidao/.test(url))
        content = content[0].firstChild && content[0].firstChild.nodeValue && content[0].firstChild.nodeValue.replace(/\<a\s+href\=['"]*[^<>]+["']*[^>]\>([^<>]+)\<\/a\>/gim, function (a, b) {
          console.log(a, b)
          return b;
        });
        var data = {
          title: title[0].firstChild.nodeValue,
          content: content,
          pic: picture[0] && picture[0].firstChild && picture[0].firstChild.nodeValue || "",
          date: date[0].firstChild.nodeValue,
          author: media[0].firstChild.nodeValue,
          subtype: subtype[0].firstChild.nodeValue
        };
        console.log(data)
        then.setData({
          title: data.title,
          date: data.date,
          author: data.author,
          subtype: data.subtype,
          picture: data.pic
        })
        /*wx.setNavigationBarTitle({
          title: data.title.substr(0, 8) + "...",
        })*/
        if (parseInt(data.subtype) !== 5) {
          WxParse.wxParse('item', 'html', data.content, then, 5);
        }
        wx.hideNavigationBarLoading()
        wx.vibrateShort()
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
      }
    })
  },
  fontSizeUp: function () {
    var size = this.data.fontSize + 1;
    size > 30 && (size = 30);
    this.setData({
      fontSize: size
    })
    wx.setStorage({
      key: 'fontsize',
      data: size,
    })
  },
  fontSizeDown: function () {
    var size = this.data.fontSize - 1;
    size < 12 && (size = 12);
    this.setData({
      fontSize: size
    })
    wx.setStorage({
      key: 'fontsize',
      data: size,
    })
  },
  previewImage: function () {
    wx.previewImage({
      current: [this.data.qrcode], // 当前显示图片的http链接   
      urls: [this.data.qrcode] // 需要预览的图片http链接列表   
    })
  },
  getAsideNews: function () {
    var then = this;
    wx.showNavigationBarLoading()
    wx.request({
      url: utils.api.asideNews.tmpl({
        id: then.data.newsId
      }),
      data: {},
      success: function (res) {
        console.log(res.data);
        if (res.data.status === 1) {
          var data = [];
          res.data.data.forEach(function (item) {
            data.push({
              title: item.title.toCN(),
              img: item.pictureUrl.replace(/http\:/gim, "https:"),
              path: "../../pages/view/view?id=" + item.id + "&chid=" + then.data.type + "&navid=" + then.data.currentNav,
              media: item.media.toCN(),
              time: item.pubTime
            })
          })
          /*if (data.length < 6) {
            wx.request({
              url: utils.api.asideNews_bigData.tmpl({
                id: then.data.newsId
              }),
              data: {},
              success: function (res) {
                if (res.data.status === 1) {
                  var i = data.length;
                  res.data.data.forEach(function (item) {
                    i + 1 <= 6 && data.push({
                      title: item.title,
                      img: item.newsmatchpic.replace(/http\:/gim, "https:"),
                      path: "../../pages/view/view?id=" + item.id + "&chid=" + then.data.type + "&navid=" + then.data.currentNav,
                      media: item.medianame,
                      time: item.entitytime
                    })
                    i += 1;
                  })
                }
                then.setData({
                  items: data
                })
              }, fail: function () {
                then.setData({
                  items: data
                })
              }
            })
          } else {*/
          then.setData({
            items: data
          })
          // }
        }
        wx.hideNavigationBarLoading()
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
      }
    });
  }
})